package cn.ad.server.web.spring.service.transmitter;

import cn.ad.server.web.spring.model.AdResponse;
import cn.ad.server.web.spring.model.ITransmitInfo;
import cn.ad.server.web.spring.service.actions.handler.gdt.server.HttpConnectionManager;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

public abstract class AbstractBaseTransmitter implements ITransmit {
	
	static final Logger LOGGER = LoggerFactory.getLogger(AbstractBaseTransmitter.class);
	
	/**
	 *连接管理器 
	 */
	@Autowired
	private HttpConnectionManager httpConnectionManager;

	
	@Override
	public AdResponse transmit(ITransmitInfo info, String url) {
		return null;
	}
	
	@Override
	public AdResponse transmit(ITransmitInfo info) {
			AdResponse resp = new AdResponse(){};
		try {
			if(!StringUtils.hasText(getUrl())){
				LOGGER.debug("第三方渠道发送的地址无效" );
				throw new Exception("系统错误：第三方渠道发送的地址无效");
				//return resp;
			}
			CloseableHttpClient httpClient = (CloseableHttpClient)getHttpClient();
			HttpGet httpGet = new HttpGet(getUrl()+ "?" + info.getTransmitInfo());
			LOGGER.debug("第三方渠道发送的地址参数：" + getUrl() + "?" + info.getTransmitInfo());
			CloseableHttpResponse response = httpClient.execute(httpGet);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				LOGGER.debug("第三方渠道" + getUrl() + "发送成功");
				resp.setStatus(HttpStatus.SC_OK);
			} else {
				LOGGER.error("失败状态：" + response.getStatusLine().getStatusCode());
				resp.setStatus(response.getStatusLine().getStatusCode());
			}

		} catch (Exception e) {
			LOGGER.error("信息发送服务异常", e);// TODO do...
			resp.setStatus(204);// TODO do...
		}
		
		return resp;
	}
	
	public HttpClient getHttpClient() {
		return httpConnectionManager.getHttpClient();
	}
	
	public HttpResponse execute(HttpGet httpGet) {
		return null;
	}
	
	public HttpResponse execute(HttpPost httpPost) {
		return null;
	}

	public abstract String getUrl();
	public abstract String getCh();

}
